import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../data/models/bt_user_info.dart';
import '../../../data/store/bt_hive_logon_store.dart';
import '../../utils/bt_constants.dart';
import '../../utils/bt_event_bus.dart';
import '../repository/bt_profile_repository.dart';

class BtProfileModel extends ChangeNotifier {
  String _userId = '';

  String get userId => _userId;

  String _nickname = '';

  String get nickname => _nickname;

  String _avatarUrl = '';

  String get avatarUrl => _avatarUrl;

  String _userServiceId = '';

  String get userServiceId => _userServiceId;

  late final BtProfileRepository repository;

  late BtUserInfo _userInfo;

  BtUserInfo get userInfo => _userInfo;

  BtProfileModel() {
    repository = BtProfileRepository();
    loadUserInfo();

    eventBus.on<BtEventFn>().listen((event) {
      if (event.refresh == 'freshUserInfo') {
        loadUserInfo();
      }
    });
  }

  Future<void> loadUserInfo() async {
    var data = await BtHiveLogonStore().getData();
    _userId = data?.userId ?? '';

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    _userServiceId = prefs.getString(userServiceAccountId) ?? '';
    notifyListeners();

    repository.freshUserInfo(_userId, data?.token ?? '', (userInfo) {
      _avatarUrl = userInfo?.avatarUrl ?? '';
      _nickname = userInfo?.nickname ?? '';
      _userInfo = userInfo!;

      notifyListeners();
    });
  }

  void logout(Function(bool success, String msg) onResult) {
    repository.logout(onResult);
  }
}
